package com.supreme.cacheserver.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.supreme.commonmybatis.entity.primary.MBAccount;
import com.supreme.commonmybatis.mapper.AccountMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class AccountService {

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private RedisTemplate<String, MBAccount> redisTemplate;

    public List<MBAccount> getAccountList() {
        return accountMapper.selectList(Wrappers.emptyWrapper());
    }

    public int insert() {
        final MBAccount mbAccount = new MBAccount();
        mbAccount.setUserId(1L);
        mbAccount.setMoney(12D);
        return accountMapper.insert(mbAccount);
    }

    public int batchInsertAccount() {
        List<MBAccount> accountList = new ArrayList<>();
        for (long i = 1; i <= 10; i++) {
            MBAccount mbAccount = new MBAccount();
            mbAccount.setUserId(i + 10);
            mbAccount.setMoney(12.5);
            accountList.add(mbAccount);
        }
        accountMapper.batchInsertAccount(accountList);
        return 0;
    }

    public void insertAccountListToRedis(String key, List<MBAccount> accountList) {
        redisTemplate.opsForList().rightPushAll(key, accountList);
    }

    public List<MBAccount> getAccountListFromRedis(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public JSONObject getAccountPagingFromRedis(String key, long page, long limit) {
        Long size = redisTemplate.opsForList().size(key);
        long start = (page - 1) * limit;
        long end = start + limit - 1;
        List<MBAccount> accountList = Optional.ofNullable(redisTemplate.opsForList().range(key, start, end)).orElse(new ArrayList<>());
        return new JSONObject().fluentPut("rows", accountList).fluentPut("count", accountList.size()).fluentPut("total", size);
    }

    public MBAccount getAccountByIndex(String key, int index) {
        return redisTemplate.opsForList().index(key, index);
    }
}
